<template>
  <div class="search-suggestion">
    <van-cell
      icon="search"
      v-for="(str, index) in suggestions"
      :key="index"
      @click="$emit('search', str.title)"
    >
      <div slot="title" v-html="highlight(str.title)"></div>
    </van-cell>
  </div>
</template>

<script>
import { debounce } from 'lodash'

export default {
  components: {},
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      suggestions: [],
      htmlStr: 'Hello <span style="color: red">World</span>'
    }
  },
  computed: {},
  watch: {
    searchText: {
      handler: debounce(async function () {
        this.$http('api/tableTest/page', {
          params: {
            page: 1,
            limit: 20,
            name: this.searchText,
            field: 'title'
          }
        }).then(({ data: res }) => {
          if (res.code === 0) this.suggestions = res.data
        })
      }, 200),
      immediate: true
    }
  },
  created () {},
  mounted () {},
  methods: {
    highlight (str) {
      return str.replace(
        new RegExp(this.searchText, 'gi'),
        `<span style="color: red">${this.searchText}</span>`
      )
    }
  }
}
</script>

<style scoped lang="less"></style>
